from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from goods.models import SKUImage,SKU
from celery_tasks.static_html.tasks import get_detail_html
#
class SKUImageSerializer(serializers.ModelSerializer):
    sku = serializers.PrimaryKeyRelatedField(read_only=True)
    class Meta:
        model = SKUImage
        # fields = ('id','sku','image')
        fields = '__all__'
#重写create方法,图片上传到fasdDFS中
    def create(self, validated_data):
#         建立连接对象
        client = Fdfs_client(settings.FASRTDFS_PATH)
#         获取数据
        request = self.context['request']
        image_file = request.data.get('image')
#         上传图片
        res = client.upload_by_buffer(image_file.read())
#         判断返回结果
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        image_url = res['Remote file_id']
        img = SKUImage.objects.create(image=image_url, sku_id=request.data['sku'])
#           返回保存后的图片对象数据
#         详情页面静态化
        sku = SKU.objects.get(id=request.data['sku'])
        if not sku.default_image:
            sku.default_image = image_url
            sku.save()
        get_detail_html.delay(request.data['sku'])
        return img
#
# 重写updata方法
    def update(self, instance, validated_data):
        client = Fdfs_client(settings.FASRTDFS_PATH)
        #         获取数据
        request = self.context['request']
        image_file = request.data.get('image')
        #         上传图片
        res = client.upload_by_buffer(image_file.read())
        #         判断返回结果
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        # s
        image_url = res['Remote file_id']
        instance.image = image_url
        instance.sku_id = request.data['sku']
        instance.save()
        #           返回保存后的图片对象数据(页面静态化)
        sku = SKU.objects.get(id=request.data['sku'])
        if not sku.default_image:
            sku.default_image = image_url
            sku.save()
        get_detail_html.delay(request.data['sku'])
        return instance

class SKUSerializer(serializers.ModelSerializer):
    class Meta:
        model=SKU
        fields=('id','name')